<template>
  <div class="admin-products">
    <header class="header">
      <div class="container">
        <div class="logo">
          <h1>拼多多 - 商品管理</h1>
        </div>
        <nav class="nav">
          <router-link to="/">返回首页</router-link>
          <router-link to="/admin/products">商品管理</router-link>
          <router-link to="/admin/users">用户管理</router-link>
          <router-link to="/admin/cart">购物车管理</router-link>
          <router-link to="/admin/categories">分类管理</router-link>
        </nav>
      </div>
    </header>

    <div class="container">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>商品管理</span>
            <el-button type="primary" @click="handleAdd">添加商品</el-button>
          </div>
        </template>

        <el-table :data="products" style="width: 100%">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="price" label="价格" width="120">
            <template #default="scope">
              ¥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="100" />
          <el-table-column prop="category_id" label="分类ID" width="100" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 添加/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
      >
        <el-form :model="form" label-width="80px">
          <el-form-item label="商品名称">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="价格">
            <el-input-number v-model="form.price" :min="0" :precision="2" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="form.description" type="textarea" />
          </el-form-item>
          <el-form-item label="商品图片">
            <el-upload
              class="image-uploader"
              action="http://localhost:3000/api/upload"
              name="image"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
            >
              <img v-if="form.image" :src="form.image" class="uploaded-image" />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="image-tip">建议尺寸：800x800px，支持jpg/png/gif，大小不超过5MB</div>
          </el-form-item>
          <el-form-item label="分类ID">
            <el-input-number v-model="form.category_id" :min="1" />
          </el-form-item>
          <el-form-item label="库存">
            <el-input-number v-model="form.stock" :min="0" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '../../utils/request'

const products = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加商品')
const form = ref({
  id: null,
  name: '',
  price: 0,
  description: '',
  image: '',
  category_id: 1,
  stock: 0
})

const loadProducts = async () => {
  try {
    const res = await request.get('/products')
    products.value = res.data || []
  } catch (error) {
    ElMessage.error('加载商品失败')
  }
}

const handleAdd = () => {
  dialogTitle.value = '添加商品'
  form.value = {
    id: null,
    name: '',
    price: 0,
    description: '',
    image: '',
    category_id: 1,
    stock: 0
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑商品'
  form.value = { ...row }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  try {
    if (form.value.id) {
      await request.put(`/products/${form.value.id}`, form.value)
      ElMessage.success('更新成功')
    } else {
      await request.post('/products', form.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    loadProducts()
  } catch (error) {
    ElMessage.error(form.value.id ? '更新失败' : '添加失败')
  }
}

const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await request.delete(`/products/${id}`)
    ElMessage.success('删除成功')
    loadProducts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 图片上传前验证
const beforeUpload = (file) => {
  const isImage = /^image\/(jpeg|png|gif|webp)$/.test(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 图片上传成功
const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    form.value.image = response.data.url
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败')
  }
}

// 图片上传失败
const handleUploadError = () => {
  ElMessage.error('图片上传失败，请重试')
}

onMounted(() => {
  loadProducts()
})
</script>

<style scoped>
.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 15px 0;
  margin-bottom: 20px;
}

.header .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo h1 {
  color: #E02E24;
  font-size: 20px;
}

.nav {
  display: flex;
  gap: 20px;
}

.nav a {
  text-decoration: none;
  color: #333;
}

.nav a.router-link-active {
  color: #E02E24;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-uploader:hover {
  border-color: #E02E24;
}

.uploaded-image {
  width: 178px;
  height: 178px;
  object-fit: cover;
  display: block;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.image-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}
</style>

